// backend/src/routes/recompute.cjs
// 重算路由模块 - 从 server-simple.cjs 中拆分出来
// 遵循生产级规则：绝对路径、完整错误处理、直连真实数据库

const express = require('express');
const router = express.Router();

// 引入重算业务模块
const { startRecomputeJob, initializeDbPool } = require('../../recompute/jobs.cjs');

// 数据库连接池引用（由主服务传入）
let dbPool = null;

// 初始化数据库连接池
function setDbPool(pool) {
  dbPool = pool;
  initializeDbPool(pool);
}

// POST /api/recompute/jobs/start - 启动重算任务
router.post('/jobs/start', express.json(), async (req, res) => {
  try {
    if (!dbPool) {
      return res.status(500).json({ success: false, error: 'Database not initialized' });
    }

    const p = req.body || {};

    // 输入参数校验
    const isStr = v => typeof v === 'string' && v.trim().length > 0;
    const isStrArr = a => Array.isArray(a) && a.every(x => typeof x === 'string' && x.trim().length > 0);

    if ((p.from_date && !isStr(p.from_date)) ||
        (p.to_date && !isStr(p.to_date)) ||
        (p.line_names && !isStrArr(p.line_names)) ||
        (p.material_codes && !isStrArr(p.material_codes))) {
      return res.status(400).json({ success: false, error: 'invalid input' });
    }

    // 调用业务模块
    const result = await startRecomputeJob(p, dbPool);
    return res.json({ success: true, ...result });

  } catch (e) {
    try {
      console.error('启动重算任务失败(router):', e && (e.message || e));
    } catch (_) {}
    return res.status(500).json({
      success: false,
      error: e && (e.message || String(e))
    });
  }
});

// GET /api/recompute/jobs - 查询重算任务列表
router.get('/jobs', async (req, res) => {
  try {
    if (!dbPool) {
      return res.status(500).json({ success: false, error: 'Database not initialized' });
    }

    const limit = Math.max(1, Math.min(200, parseInt(req.query.limit || '20')));
    const rows = await dbPool.query(
      `SELECT id,status,total,processed,updated,batch_size,started_at,finished_at,created_at,filter_json,error
       FROM recompute_jobs ORDER BY created_at DESC LIMIT ?`,
      [limit]
    );

    return res.json({ success: true, jobs: rows });

  } catch (e) {
    try {
      console.error('查询重算任务列表失败(router):', e && (e.message || e));
    } catch (_) {}
    return res.status(500).json({
      success: false,
      error: e && (e.message || String(e))
    });
  }
});

// GET /api/recompute/jobs/:id - 查询重算任务详情
router.get('/jobs/:id', async (req, res) => {
  try {
    if (!dbPool) {
      return res.status(500).json({ success: false, error: 'Database not initialized' });
    }

    const { id } = req.params;
    const rows = await dbPool.query(
      'SELECT id, status, total, processed, updated, batch_size, started_at, finished_at, created_at, filter_json, error FROM recompute_jobs WHERE id=?',
      [id]
    );

    if (!rows.length) {
      return res.status(404).json({ success: false, error: 'not found' });
    }

    return res.json({ success: true, job: rows[0] });

  } catch (e) {
    try {
      console.error('查询重算任务详情失败(router):', e && (e.message || e));
    } catch (_) {}
    return res.status(500).json({
      success: false,
      error: e && (e.message || String(e))
    });
  }
});

// POST /api/recompute/jobs/:id/cancel - 取消重算任务
router.post('/jobs/:id/cancel', async (req, res) => {
  try {
    if (!dbPool) {
      return res.status(500).json({ success: false, error: 'Database not initialized' });
    }

    const { id } = req.params;
    await dbPool.query(
      'UPDATE recompute_jobs SET status=\'cancelled\', finished_at=CURRENT_TIMESTAMP WHERE id=?',
      [id]
    );

    return res.json({ success: true });

  } catch (e) {
    try {
      console.error('取消重算任务失败(router):', e && (e.message || e));
    } catch (_) {}
    return res.status(500).json({
      success: false,
      error: e && (e.message || String(e))
    });
  }
});

// 导出路由和初始化函数
module.exports = {
  router,
  setDbPool
};
